package com.security.it.authentication.config;

import com.security.it.authentication.handler.SelfAuthenticationFailureHandler;
import com.security.it.authentication.handler.SelfAuthenticationSuccessHandler;
import com.security.it.authentication.mobile.SmsAuthenticationFilter;
import com.security.it.authentication.mobile.SmsAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class SmsAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private SelfAuthenticationFailureHandler selfAuthenticationFailureHandler;
    @Autowired
    private SelfAuthenticationSuccessHandler selfAuthenticationSuccessHandler;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) {
        // 验证码过滤器
        SmsAuthenticationFilter smsAuthFilter = new SmsAuthenticationFilter();
        smsAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsAuthFilter.setAuthenticationSuccessHandler(selfAuthenticationSuccessHandler);
        smsAuthFilter.setAuthenticationFailureHandler(selfAuthenticationFailureHandler);
        // 自定义Provider
        SmsAuthenticationProvider smsProvider = new SmsAuthenticationProvider();
        smsProvider.setUserDetailsService(userDetailsService);

        http.authenticationProvider(smsProvider)
                .addFilterAfter(smsAuthFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
